# coding:utf-8
import logging
from logging import FileHandler, StreamHandler, Formatter, handlers
__name__ = 'logger_time_bytes'

"""
# 按时间
# 按日期
# 本脚本支持以上两种方式存储日志文件

# set message with the specified log level

# 使用默认参数初始化Logger
Logger.init_log()

Logger.debug(message)
Logger.info(message)
Logger.warning(message)
Logger.error(message)
Logger.critical(message)
"""


class Logger:
    log = None
    # 默认：'%(asctime)s [%(name)s] %(levelname)s: %(message)s'
    format = '%(asctime)s|[%(name)s]|%(levelname)s: %(message)s'

    @classmethod
    def init_logger(cls, timed_rotate=True, bytes_rotate=False, filename='log.log', when='d', interval=1, log_level=4, backupCount=0, encoding=None, delay=None, mode='a', maxBytes=0):
        """
        按时间记录或者按大小生成日志文件
        timed_rotate=True的时候按时间生成日志文件 / bytes_rotate为
        :param timed_rotate: True or False 代表是否按照时间生成日志文件
        :param bytes_rotate: Truw or False 代表是否按照文件大小生成日志文件
        :param filename: 日志文件名
        :param when: s/m/h/d（时间单位） 常用四种，还有两种，使用的话查看源码。
        :param interval: 生成日志的时间间隔
        :param log_level: 日志记录的日志级别
        :param backupCount: 备份的日志文件数量，默认删除最早的日志
        :param encoding: 编码格式
        :param delay: 延迟
        :param mode: 文件的读写模式
        :param maxBytes: 最大的Byte数
        :return:
        """
        # 设置一个log_level
        level = (
            logging.CRITICAL,
            logging.ERROR,
            logging.WARNING,
            logging.INFO,
            logging.DEBUG,
        )
        # Return a logger with the specified name
        log = logging.getLogger(__name__)
        log.setLevel(level[log_level])
        # 设置日志格式
        format = Formatter(cls.format)

        # 初始化处理程序/存储在file中/timed_rotate_file && bytes_rotate_file
        if timed_rotate:
            timed_rotate_handler = handlers.TimedRotatingFileHandler(filename='timed_' + filename, when=when, interval=interval, backupCount=backupCount, encoding=encoding, delay=delay)
            timed_rotate_handler.suffix = "%Y-%m-%d-%S.log"
            # timed_rotate_handler.setLevel(logging.DEBUG)
            timed_rotate_handler.setFormatter(format)
            log.addHandler(timed_rotate_handler)

        if bytes_rotate:
            bytes_rotate_handler = handlers.RotatingFileHandler(filename='file_' + filename, mode=mode, maxBytes=maxBytes, backupCount=backupCount)
            # bytes_rotate_handler.setLevel(logging.DEBUG)
            bytes_rotate_handler.setFormatter(format)
            log.addHandler(bytes_rotate_handler)

        # 初始化cls.log
        cls.log = log

    @classmethod
    def debug(cls, message):
        cls.log.debug(message)

    @classmethod
    def info(cls, message):
        cls.log.info(message)

    @classmethod
    def warning(cls, message):
        cls.log.warning(message)

    @classmethod
    def error(cls, message):
        cls.log.error(message)

    @classmethod
    def critical(cls, message):
        cls.log.critical(message)
